<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/10/17
 * Time: 14:42
 */
namespace app\admin\service;
use app\common\library\Email;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
class MailService
{
    public $language    = 'en';
    //resetpwd  register  changemobile  changepwd
    public function sendEmail($email,$code,$event){

        $configData = db('config')->where('group','email')->select();
        $config = [];
        foreach ($configData as $item){
            $name = $item['name'];
            $config[$name] = $item['value'];
        }
        $mail = new PHPMailer(true);

        /*$fp = fsockopen("smtp.qq.com",25,$errno,$errstr,60);
        if(! $fp)
            echo '$errstr ($errno) <br> \n ';
        else
            echo 'ok <br> \n ';
        ppd('fini');*/
        /**
         *
         * 在godaddy上买的邮箱，，有两种如下方式
         * outlook邮箱
         * 服务器名称: smtp.office365.com
        端口: 587
        加密方法: STARTTLS  tls
         *
         * smtpout.secureserver.net
         * 465
         * SSL
         *
         * zoho邮箱
         * smtppro.zoho.com
        港口
        465 带 SSL 或 587 带 TLS
        465 带 SSL 或 587 带 TLS
         *
         *
         * aliyun
         *  $data['email_host'] = "ssl://smtpdm.aliyun.com";
        $data['email_user'] = 'support@redefiningbox.com';
        $data['email_pwd'] = 'ASdf778899';
        $data['email_port'] = '465';
        $data['to_user'] = '78540125@qq.com';
        $data['to_user_name'] = 'kevin.kiu';
        $data['title'] = 'ceshiyieg 文章';
        $data['body'] = 'ceshiyieg 文章ceshiyieg 文章';
         */
        $email_host = $config['mail_smtp_host'];
        $email_user = $config['mail_smtp_user'];
        $email_pwd = $config['mail_smtp_pass'];
        $email_port = $config['mail_smtp_port'];
        if(empty($email_pwd)){
            return '';
        }

        $this->language = request()->langset();
        if($this->language == 'zh-hk'){
            $title = "【SPACESTUDIO】註冊驗證";
            $content = "【SPACESTUDIO】您正在注冊，驗證碼是：{$code}，3分鐘内有效。";
        }else if($this->language == 'zh-en'){
            $title = "【SPACESTUDIO】注册验证";
            $content = "【SPACESTUDIO】您正在注册，验证码是：{$code}，3分钟内有效。";
        }else{
            $title = "【SPACESTUDIO】Registration verification";
            $content = "【SPACESTUDIO】You are registering,the verification code is：{$code}，effective within 3 minutes";
        }

        if($event == 'resetpwd'){
            if($this->language == 'zh-hk'){
                $title = "【SPACESTUDIO】重置密碼驗證";
                $content = "【SPACESTUDIO】您正在重置密碼，驗證碼是：{$code}，3分鐘有效。";
            }else if($this->language == 'zh-en'){
                $title = "【SPACESTUDIO】重置密码验证";
                $content = "【SPACESTUDIO】您正在重置密码，验证码是：{$code}，3分钟有效。";
            }else{
                $title = "【SPACESTUDIO】Reset password verification";
                $content = "【SPACESTUDIO】You are resetting your password,the verification code is：{$code}，effective within 3 minutes";
            }
        }

        $to_user    = $email;
        $to_user_name    = $email;
        $body            = $content;
        $reply_email     = $email_user;

        //465（需要SSL）、587（需要TLS）
        $ssl = 'tls';
        if($config['mail_verify_type'] == 1){
            $ssl = 'TLS';
        }else{
            $ssl = 'SSL';
        }

        $email = new Email;
        $result = $email
            ->to($to_user)
            ->from($email_user,'SpaceStudio')
            ->subject($title)
            ->message($body)
            ->send();
        if ($result) {
            return array('code'=>0,'msg'=>'发送成功');
        } else {
            return array('code'=>1005,'msg'=>$email->getError());
        }

        try {
            //Server settings
            $mail->CharSet ="UTF-8";                                    //设定邮件编码
            $mail->SMTPDebug = 0;                      //Enable verbose debug output 0关闭  1  2
            $mail->isSMTP();                                            //Send using SMTP
//            $mail->Host       = 'ssl://smtp.gmail.com:465';                     //25 Set the SMTP server to send through
            $mail->Host       = $email_host;                     //587 Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
            $mail->Username   = $email_user;                     //SMTP username
            $mail->Password   = $email_pwd;                               //SMTP password
            $mail->SMTPSecure = $ssl;                                      //Enable implicit TLS encryption  允许 TLS 或者ssl协议
            $mail->Port       = $email_port;                                    //465 TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

            //Recipients
            $mail->setFrom($email_user, 'SpaceStudio');
            $mail->addAddress($to_user, $to_user_name);     //Add a recipient
//            $mail->addAddress('ellen@example.com');               //Name is optional  可添加多个收件人
            $mail->addReplyTo($reply_email, 'SpaceStudio');//回复的时候回复给哪个邮箱 建议和发件人一致
//            $mail->addCC('cc@example.com');                    //抄送
//            $mail->addBCC('bcc@example.com');                     //密送

            //Attachments
//            $mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments
//            $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name

            //Content
            $mail->isHTML(true);                                  //Set email format to HTML
            $mail->Subject = $title;
            $mail->Body    = $body;
//            $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

            $res = $mail->send();
            if($res){
                return array('code'=>0,'msg'=>'Send Success');
            }else{
                return array('code'=>1005,'msg'=>'Send Failed');
            }
        } catch (Exception $e) {
            $info =  "Mailer Error: {$mail->ErrorInfo}";
            return array('code'=>1005,'msg'=>$info);
        }
    }

    public function sendYeyueEmail($email,$title,$content){
        $configData = db('config')->where('group','email')->select();
        $config = [];
        foreach ($configData as $item){
            $name = $item['name'];
            $config[$name] = $item['value'];
        }
        $mail = new PHPMailer(true);

        $email_host = $config['mail_smtp_host'];
        $email_user = $config['mail_smtp_user'];
        $email_pwd = $config['mail_smtp_pass'];
        $email_port = $config['mail_smtp_port'];
        if(empty($email_pwd)){
            return '';
        }

        $this->language = request()->langset();


        $to_user    = $email;
        $to_user_name    = $email;
        $body            = $content;
        $reply_email     = $email_user;

        $email = new Email;
        $result = $email
            ->to($to_user)
            ->from($email_user,'SpaceStudio')
            ->subject($title)
            ->message($body)
            ->send();
        if ($result) {
            return array('code'=>0,'msg'=>'发送成功');
        } else {
            return array('code'=>1005,'msg'=>$email->getError());
        }
        try {
            //Server settings
            $mail->CharSet ="UTF-8";                                    //设定邮件编码
            $mail->SMTPDebug = 1;                      //Enable verbose debug output 0关闭  1  2
//            $mail->isSMTP();                                            //Send using SMTP
//            $mail->Host       = 'ssl://smtp.gmail.com:465';                     //25 Set the SMTP server to send through
            $mail->Host       = $email_host;                     //587 Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
            $mail->Username   = $email_user;                     //SMTP username
            $mail->Password   = $email_pwd;                               //SMTP password
            $mail->SMTPSecure = 'tls';                                      //Enable implicit TLS encryption  允许 TLS 或者ssl协议
            $mail->Port       = $email_port;                                    //465 TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

            //Recipients
            $mail->setFrom($email_user, 'SpaceStudio');
            $mail->addAddress($to_user, $to_user_name);     //Add a recipient
//            $mail->addAddress('ellen@example.com');               //Name is optional  可添加多个收件人
            $mail->addReplyTo($reply_email, 'SpaceStudio');//回复的时候回复给哪个邮箱 建议和发件人一致
//            $mail->addCC('cc@example.com');                    //抄送
//            $mail->addBCC('bcc@example.com');                     //密送

            //Attachments
//            $mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments
//            $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name

            //Content
            $mail->isHTML(true);                                  //Set email format to HTML
            $mail->Subject = $title;
            $mail->Body    = $body;
//            $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

            $res = $mail->send();
            if($res){
                return array('code'=>0,'msg'=>'Send Success');
            }else{
                return array('code'=>1005,'msg'=>'Send Failed');
            }
        } catch (Exception $e) {
            $info =  "Mailer Error: {$mail->ErrorInfo}";
            return array('code'=>1005,'msg'=>$info);
        }
    }
    public function formateMailMsg($body,$sys,$order){
//        ppd($order);
        $productArr = json_decode($order['product_json'],true);
        $addressArr = json_decode($order['custom_json'],true);
        $address = $addressArr['address']." - ".$addressArr['state'].' '.$addressArr['city'].' '.$addressArr['country'];
        $custom_name = $addressArr['first_name'].' '.$addressArr['last_name'];

        $delivery_code = '';
        if(!empty($order['delivery_id'])){
            $delivery_code = DB::table('delivery')->where('id',$order['delivery_id'])->value('delivery_code');
        }
        $productA = [];
        $product_urlA = [];
        $image = [];
        $shuxing = [];
        foreach ($productArr as $item){
            $productA[] = $item['title'];
            $image[] = isset($item['image_url']) ? $item['image_url'] : '';
            $product_urlA[] = isset($item['product_url']) ? $item['product_url'] : '';
            $shuxing[] = isset($item['products_attributes']) ? $item['products_attributes'] : '';
        }
        if(empty($productA)){
            $product = '';
            return '';
        }else{
            $product = $productA[0];
        }
        if(empty($product_urlA)){
            $product_url = '';
            return '';
        }else{
            $product_url = $product_urlA[0];
        }
        if(empty($image)){
            $image = '';
        }else{
            $image = implode(' / ',$image);
        }
        if(empty($shuxing)){
            $shuxing = '';
        }else{
            $shuxing = implode(' / ',$shuxing);
        }
        $email_info_key_arr = config('global.email_info_key');
        $relation_data = [];
        foreach ($email_info_key_arr as $value){
            switch ($value){
                case '[service_email]':
                    $relation_data[$value] = $sys['email'];
                    break;
                case '[user]':
                    $relation_data[$value] = $custom_name;
                    break;
                case '[orderno]':
                    $relation_data[$value] = $order['orderid'];
                    break;
                case '[email]':
                    $relation_data[$value] = $order['email'];
                    break;
                case '[address]':
                    $relation_data[$value] = $address;
                    break;
                case '[title]':
                    $relation_data[$value] = "<a href='{$product_url}' target='_blank'>$product</a>";
                    break;
                case '[price]':
                    $relation_data[$value] = $order['money'];
                    break;
                case '[image]':
                    $relation_data[$value] = $image;
                    break;
                case '[shuxing]':
                    $relation_data[$value] = $shuxing;
                    break;
                case '[delivery_no]':
                    $relation_data[$value] = $order['delivery_no'];
                    break;
                case '[delivery_code]':
                    $relation_data[$value] = $delivery_code;
                    break;
            }
        }

        foreach ($relation_data as $key=>$value){
            $body = str_replace($key,$value,$body);
        }
        return $body;
    }

    public function sendEmail2($data){
        $mail = new PHPMailer(true);

        /*$fp = fsockopen("smtp.qq.com",25,$errno,$errstr,60);
        if(! $fp)
            echo '$errstr ($errno) <br> \n ';
        else
            echo 'ok <br> \n ';
        ppd('fini');*/
        /**
         * info@spacestudiohk.net
         * Space0321
         * outlook邮箱
         * 服务器名称: smtp.office365.com
        端口: 587
        加密方法: STARTTLS  tls
         *
         *
         * info@spacestudiohk.com
         * Space0321
         * 服务器名称：smtpout.secureserver.net
         * 端口： 465
         * SSL
         *
         * zoho邮箱
         * smtppro.zoho.com
        港口
        465 带 SSL 或 587 带 TLS
         *
         *
         * aliyun
         *  $data['email_host'] = "ssl://smtpdm.aliyun.com";
        $data['email_user'] = 'support@redefiningbox.com';
        $data['email_pwd'] = 'ASdf778899';
        $data['email_port'] = '465';
        $data['to_user'] = 'sssssssss@qq.com';
        $data['to_user_name'] = 'kevin.kiu';
        $data['title'] = 'ceshiyieg 文章';
        $data['body'] = 'ceshiyieg 文章ceshiyieg 文章';
         */
        $email_host = $data['email_host'];
        $email_user = $data['email_user'];
        $email_pwd  = $data['email_pwd'];
        $email_port = $data['email_port'];
        if(empty($email_pwd)){
            return '';
        }
        $to_user    = $data['to_user'];
        $to_user_name    = $data['to_user_name'];
        $title           = $data['title'];
        $body            = $data['body'];
        $reply_email     = 'support.mary@goodforlifes.com';

        /*$email = new Email;
        $result = $email
            ->to($to_user)
            ->from($email_user,'SpaceStudio')
            ->subject($title)
            ->message($body)
            ->send();
        if ($result) {
            return array('code'=>0,'msg'=>'发送成功');
        } else {
            return array('code'=>1005,'msg'=>$email->getError());
        }*/
        try {
            //Server settings
            $mail->CharSet ="UTF-8";                                    //设定邮件编码
            $mail->SMTPDebug = 1;                      //Enable verbose debug output 0关闭  1  2
//            $mail->isMail();                                            //Send using SMTP
            $mail->isSMTP();                                            //Send using SMTP
//            $mail->Host       = 'ssl://smtp.gmail.com:465';                     //25 Set the SMTP server to send through
            $mail->Host       = $email_host;                     //587 Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
            $mail->Username   = $email_user;                     //SMTP username
            $mail->Password   = $email_pwd;                               //SMTP password
            $mail->SMTPSecure = 'tls';   //tls                                   //Enable implicit TLS encryption  允许 TLS 或者ssl协议
            $mail->Port       = $email_port;                                    //465 TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

            //Recipients
            $mail->setFrom($email_user, 'Darren Allison');
            $mail->addAddress($to_user, $to_user_name);     //Add a recipient
//            $mail->addAddress('ellen@example.com');               //Name is optional  可添加多个收件人
            $mail->addReplyTo($reply_email, 'Darren Allison');//回复的时候回复给哪个邮箱 建议和发件人一致
//            $mail->addCC('cc@example.com');                    //抄送
//            $mail->addBCC('bcc@example.com');                     //密送

            //Attachments
//            $mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments
//            $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name

            //Content
            $mail->isHTML(true);                                  //Set email format to HTML
            $mail->Subject = $title;
            $mail->Body    = $body;
//            $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

            $res = $mail->send();
            if($res){
                return array('code'=>0,'msg'=>'发送成功');
            }else{
                return array('code'=>1005,'msg'=>'发送失败');
            }
        } catch (Exception $e) {
            $info =  "Mailer Error: {$mail->ErrorInfo}";
            return array('code'=>1005,'msg'=>$info);
        }
    }
}
